﻿using MayhemServer.Services;
using NuGet.Server.DataServices;
using NuGet;
using System;
using System.Linq;

namespace MayhemServer.Extensions {
    public static class PackageExtensions {
        public static string GetTitle(this Package package) {
            if (!string.IsNullOrEmpty(package.Title)) {
                return package.Title;
            }

            return package.Id;
        }

        public static string GetShortDescription(this Package package) {
            return GetShortDescription(package, 200);
        }

        public static string GetShortDescription(this Package package, int length) {
			// Try to use the summary first if it is set.
			string text = package.Summary;
			if (string.IsNullOrEmpty(package.Summary))
			{
				if (string.IsNullOrEmpty(package.Description)) 
				{
					return "";
				}
				else
				{
					text = package.Description;
				}
			}

			if (text.Length <= length) {
                return text;
            }

            return string.Format("{0}...", text.Substring(0, length));
        }

        public static string GetDownloadRedirectUrl(this Package package) {
            var packageDownloadService = new PackageDetailService() as IPackageDetailService;
            return string.Format("~/nupkg-redir/{0}", packageDownloadService.GetPackageDetailId(package));
        }

		public static string GetCodeplexDownloadUrl(this Package package, string downloadUrl)
		{
			// Ideally we shouldn't have to pass in the downloadUrl since this is an extension method.
			string codeplexUrl = @"http://mayhem.codeplex.com/releases/clickonce/Mayhem.application";
			return string.Format("{0}?addon={1}", codeplexUrl, downloadUrl);
		}

        public static string GetDownloadUrl(this Package package) {
            return string.Format("~/Packages/{0}.nupkg", package.GetFileName());
        }

        public static string GetFileName(this Package package)
        {
            return string.Format("{0}.{1}", package.Id, package.Version);
        }

        public static bool IsDeveloperPackage(this Package package)
        {
            return CheckDeveloperTag(package.Tags);
        }

        public static bool IsDeveloperPackage(this IPackage package)
        {
            return CheckDeveloperTag(package.Tags);
        }

        private static bool CheckDeveloperTag(string tags)
        {
			if (string.IsNullOrWhiteSpace(tags))
				return false;

            return tags.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Contains("developer", StringComparer.InvariantCultureIgnoreCase);
        }
    }
}